package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.heima.apis.article.IArticleClient;
import com.heima.common.aliyun.GreenImageScan;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.common.exception.CustomException;
import com.heima.common.tess4j.Tess4jClient;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmSensitive;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.SensitiveWordUtil;
import com.heima.wemedia.mapper.WmChannelMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmSensitiveMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsService;
import net.sourceforge.tess4j.TesseractException;
import org.springframework.beans.BeanUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class WmNewsAutoScanServiceImpl implements WmNewsAutoScanService {

    @Resource
    private WmNewsService wmNewsService;
    @Resource
    private GreenTextScan greenTextScan;
    @Resource
    private GreenImageScan greenImageScan;
    @Resource
    private WmNewsMapper wmNewsMapper;
    @Resource
    private FileStorageService fileStorageService;
    @Resource
    private WmChannelMapper wmChannelMapper;
    @Resource
    private WmUserMapper wmUserMapper;
    @Resource
    private IArticleClient iArticleClient;
    @Resource
    private WmSensitiveMapper wmSensitiveMapper;
    @Resource
    private Tess4jClient tess4jClient;

    @Override
    @Async
//    @GlobalTransactional
    public void autoScanWmNews(Integer id) {
        //根据文章id查询文章数据
        WmNews wmNews = wmNewsService.getById(id);
        //如果文章为空 抛出异常
        if (null == wmNews) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //判断文章当前的状态是否是待审核 如果是则审核 如果不是则不处理
        if (wmNews.getStatus().equals(WmNews.Status.SUBMIT.getCode())) {
            //从文章数据中抽取所有的文本内容和图片内容
            Map<String, Object> data = handleTextAndImages(wmNews);


            //自管理的敏感词过滤
            boolean isSensitive = handleSensitiveScan(data.get("content").toString(), wmNews);
            if (!isSensitive) return;

            //把文本内容交给阿里云审核 如果审核失败 则更新文章的审核状态（返回结果为布尔）
            boolean flag = handleTextScan(data.get("content").toString(), wmNews);
            if (!flag) {
                return;
            }
            //把所有的图片交给阿里云审核 如果审核失败 则更新文章的审核状态
            flag = handleImageScan((List<String>) data.get("images"), wmNews);
            if (!flag) {
                return;
            }
            //4.审核成功，保存app端的相关的文章数据
            ResponseResult responseResult = saveAppArticle(wmNews);
            if (!responseResult.getCode().equals(200)) {
                throw new RuntimeException("WmNewsAutoScanServiceImpl-文章审核，保存app端相关文章数据失败");
            }

            //回填article_id
            wmNews.setArticleId((Long) responseResult.getData());
            updateWmNews(wmNews, (short) 9, "审核成功");

        }
    }

    private boolean handleSensitiveScan(String content, WmNews wmNews) {
        //查询所有的敏感词
        List<WmSensitive> wmSensitives = wmSensitiveMapper.selectList(null);
        List<String> list = wmSensitives.stream().map(wmSensitive -> wmSensitive.getSensitives()).collect(Collectors.toList());
        //初始话DFA算法的map
        SensitiveWordUtil.initMap(list);
        //通过这个map审核文本内容
        Map<String, Integer> map = SensitiveWordUtil.matchWords(content);
        //处理审核的结果
        if (map.size() > 0) {
            updateWmNews(wmNews, (short) 2, JSONObject.toJSONString(map));
            return false;

        }
        return true;

    }

    private ResponseResult saveAppArticle(WmNews wmNews) {
        ArticleDto dto = new ArticleDto();
        //属性的拷贝
        BeanUtils.copyProperties(wmNews, dto);
        //文章的布局
        dto.setLayout(wmNews.getType());
        //频道
        WmChannel wmChannel = wmChannelMapper.selectById(wmNews.getChannelId());
        if (wmChannel != null) {
            dto.setChannelName(wmChannel.getName());
        }

        //作者
        dto.setAuthorId(wmNews.getUserId().longValue());
        WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId());
        if (wmUser != null) {
            dto.setAuthorName(wmUser.getName());
        }

        //设置文章id
        if (wmNews.getArticleId() != null) {
            dto.setId(wmNews.getArticleId());
        }
        dto.setCreatedTime(new Date());

        ResponseResult responseResult = iArticleClient.saveArticle(dto);
        return responseResult;
    }

    private boolean handleImageScan(List<String> images, WmNews wmNews) {
        boolean flag = true;
        if (null == images || images.size() == 0) {
            return flag;
        }
        //从minio中下载所有的图片
        images = images.stream().distinct().collect(Collectors.toList());
        ArrayList<byte[]> imagesByteList = new ArrayList<>(images.size());
        for (String imageUrl : images) {
            byte[] bytes = fileStorageService.downLoadFile(imageUrl);
            //orc识别图片文字
            BufferedImage image = null;
            String content=null;
            try {
                image = ImageIO.read(new ByteArrayInputStream(bytes));
                content = tess4jClient.doOCR(image);
            } catch (IOException | TesseractException e) {
                throw new RuntimeException(e);
            }
            boolean sensitiveScan = handleSensitiveScan(content, wmNews);
            if (!sensitiveScan){
                return flag;
            }
            imagesByteList.add(bytes);
        }
        //调用阿里云审核结构
        try {
            Map map = greenImageScan.imageScan(imagesByteList);
            if (map != null) {
                if (map.get("suggestion").equals("block")) {
                    flag = false;
                    updateWmNews(wmNews, (short) 2, "图片中包含了违规的数据");
                } else if (map.get("suggestion").equals("review")) {
                    flag = false;
                    updateWmNews(wmNews, (short) 2, "图片中包含了不确定的数据，需人工审核");
                }
            }
        } catch (Exception e) {
            flag = false;
            e.printStackTrace();
        }
        return flag;
    }

    private boolean handleTextScan(String content, WmNews wmNews) {
        boolean flag = true;
        if (content == null) {
            return flag;
        }
        try {
            Map map = greenTextScan.greeTextScan((wmNews.getTitle()) + "-" + content);
            if (map != null) {
                //审核失败
                if (map.get("suggestion").equals("block")) {
                    flag = false;
                    updateWmNews(wmNews, (short) 2, "当前文章中存在违规内容");
                }
                //不确定信息 需要人工审核
                if (map.get("suggestion").equals("review")) {
                    flag = false;
                    updateWmNews(wmNews, (short) 3, "当前文章中存在不确定内容");
                }
            }
        } catch (Exception e) {
            flag = false;
            e.printStackTrace();
        }
        return flag;
    }

    private void updateWmNews(WmNews wmNews, short status, String reason) {
        wmNews.setStatus(status);
        wmNews.setReason(reason);
        wmNewsMapper.updateById(wmNews);
    }

    private Map<String, Object> handleTextAndImages(WmNews wmNews) {
        StringBuilder content = new StringBuilder();
        ArrayList<String> images = new ArrayList<>();
        //追加标题文本
        content.append(wmNews.getTitle() + "-");
        //添加封面图片
        if (!StringUtils.isEmpty(wmNews.getImages())) {
            images.addAll(Arrays.asList(wmNews.getImages().split(",")));
        }
        //处理内容数据
        List<Map> mapList = JSONObject.parseArray(wmNews.getContent(), Map.class);
        for (Map map : mapList) {
            if (map.get("type").equals("text")) {
                content.append(map.get("value").toString() + "-");
            } else {
                images.add(map.get("value").toString());
            }
        }
        HashMap<String, Object> result = new HashMap<>();
        result.put("content", content);
        result.put("images", images);
        return result;
    }
}
